package com.uzai.console.service.user.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.entity.WechatUser;
import com.uzai.common.entity.WxworkUser;
import com.uzai.common.enums.GroupSendStatusEnum;
import com.uzai.common.enums.MerConfigKeyEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.dto.user.wechatuser.TimeVO;
import com.uzai.console.dto.user.wechatuser.WechatUserUpdateDto;
import com.uzai.console.dto.user.wechatuser.WechatUserUpdateMarketingRewardByQueryResultDto;
import com.uzai.console.dto.user.wxworkuser.*;
import com.uzai.console.dto.wechatwork.devicewxworkinfo.DeviceWxworkInfoQuery;
import com.uzai.console.entity.*;
import com.uzai.console.enums.SmsType;
import com.uzai.console.mapper.*;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.user.MarketingRewardsBlackListService;
import com.uzai.console.service.user.WxworkUserService;
import com.uzai.console.service.user.WxworkUserSyncService;
import com.uzai.console.vo.smscode.SmsCodeVo;
import com.uzai.console.vo.user.wxworkuser.WxworkMinMaxCreateTimeVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/***
 * @author liuqi
 * @date 2021年08月25日 20:18
 */
@Service
public class WxworkUserSyncServiceImpl implements WxworkUserSyncService {

    Logger logger = LoggerFactory.getLogger(WxworkUserSyncServiceImpl.class);

    @Autowired
    private WxworkUserMapper wxworkUserMapper;
    @Autowired
    private UserTypeMapper userTypeMapper;
    @Autowired
    private WxworkUserService wxworkUserService;
    @Autowired
    private DeviceWxworkInfoMapper deviceWxworkInfoMapper;
    @Autowired
    private TbOrderMapper tbOrderMapper;
    @Autowired
    private JdOrderMapper jdOrderMapper;
    @Autowired
    private PddOrderMapper pddOrderMapper;
    @Autowired
    private VphOrderMapper vphOrderMapper;
    @Autowired
    private MtOrderMapper mtOrderMapper;
    @Autowired
    private DyOrderMapper dyOrderMapper;
    @Autowired
    private MarketingRewardsBlackListService marketingRewardsBlackListService;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private GroupSendJobMapper groupSendJobMapper;
    @Autowired
    private MerBaseConfigMapper merBaseConfigMapper;

    /**
     * 查询结果添加群发任务
     *
     * @param wxworkUserBatchSendMsgDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Async("taskExecutor")
    @Override
    public void  sendMessageToUserSelectedSync(WxworkUserBatchSendMsgDto wxworkUserBatchSendMsgDto){
        //记录发送总数
        int totalCount_parent_succ = 0;

        WxworkUserQuery wxworkUserQuery = wxworkUserBatchSendMsgDto.getWxworkUserQuery();
        wxworkUserQuery.setMerId(wxworkUserBatchSendMsgDto.getMerId());
        //查询条件中是否包含机器人id,
        if(wxworkUserQuery.getDeviceUniqueId() != null ) {//条件中带机器人id,则添加到机器人列表中
            int totalCount_son_succ = wxworkUserService.groupSendMsgByDeviceUniqueId(wxworkUserBatchSendMsgDto);
            totalCount_parent_succ = totalCount_parent_succ + totalCount_son_succ;
        }else if(wxworkUserQuery.getDeviceUniqueIdList() != null && wxworkUserQuery.getDeviceUniqueIdList().size() > 0){
            List<Long> deviceUniqueIdList = wxworkUserQuery.getDeviceUniqueIdList();
            for(Long devieUniqueId : deviceUniqueIdList){
                try {
                    WxworkUserBatchSendMsgDto wxworkUserBatchSendMsgDto_deviceUniqueId = new WxworkUserBatchSendMsgDto();
                    wxworkUserBatchSendMsgDto_deviceUniqueId.setMerId(wxworkUserBatchSendMsgDto.getMerId());
                    wxworkUserBatchSendMsgDto_deviceUniqueId.setWxworkUserGroupSendMsgDto(wxworkUserBatchSendMsgDto.getWxworkUserGroupSendMsgDto());
                    wxworkUserBatchSendMsgDto_deviceUniqueId.setGroupSendJobParentId(wxworkUserBatchSendMsgDto.getGroupSendJobParentId());
                    WxworkUserQuery wxworkUserQuery_deviceUniqueId = new WxworkUserQuery();
                    BeanUtils.copyProperties(wxworkUserQuery, wxworkUserQuery_deviceUniqueId);
                    wxworkUserQuery_deviceUniqueId.setDeviceUniqueId(devieUniqueId);
                    wxworkUserQuery_deviceUniqueId.setDeviceUniqueIdList(null);
                    wxworkUserBatchSendMsgDto_deviceUniqueId.setWxworkUserQuery(wxworkUserQuery_deviceUniqueId);
                    int totalCount_son_succ = wxworkUserService.groupSendMsgByDeviceUniqueId(wxworkUserBatchSendMsgDto_deviceUniqueId);
                    totalCount_parent_succ = totalCount_parent_succ + totalCount_son_succ;
                }catch (Exception e){
                    logger.error("-------sendMessageToUserSelectedSync is error; deviceUniqueId={}, error={}", devieUniqueId, e.getMessage());
                }
            }
        }else{//如果没有，则查询该运营商所有的机器人
            DeviceWxworkInfoQuery deviceWxworkInfoQuery = new DeviceWxworkInfoQuery();
            deviceWxworkInfoQuery.setMerId(wxworkUserBatchSendMsgDto.getMerId());
            List<DeviceWxworkInfo> deviceWxworkInfoList = deviceWxworkInfoMapper.findByList(deviceWxworkInfoQuery);
            if(deviceWxworkInfoList != null && deviceWxworkInfoList.size() > 0){
                for(DeviceWxworkInfo deviceWxworkInfo : deviceWxworkInfoList){
                    try{
                        WxworkUserBatchSendMsgDto wxworkUserBatchSendMsgDto_deviceUniqueId = new WxworkUserBatchSendMsgDto();
                        wxworkUserBatchSendMsgDto_deviceUniqueId.setMerId(wxworkUserBatchSendMsgDto.getMerId());
                        wxworkUserBatchSendMsgDto_deviceUniqueId.setWxworkUserGroupSendMsgDto(wxworkUserBatchSendMsgDto.getWxworkUserGroupSendMsgDto());
                        wxworkUserBatchSendMsgDto_deviceUniqueId.setGroupSendJobParentId(wxworkUserBatchSendMsgDto.getGroupSendJobParentId());
                        WxworkUserQuery wxworkUserQuery_deviceUniqueId = new WxworkUserQuery();
                        BeanUtils.copyProperties(wxworkUserQuery, wxworkUserQuery_deviceUniqueId);
                        wxworkUserQuery_deviceUniqueId.setMerId(wxworkUserBatchSendMsgDto.getMerId());
                        wxworkUserQuery_deviceUniqueId.setDeviceUniqueId(deviceWxworkInfo.getId());
                        wxworkUserQuery_deviceUniqueId.setDeviceUniqueIdList(null);
                        wxworkUserBatchSendMsgDto_deviceUniqueId.setWxworkUserQuery(wxworkUserQuery_deviceUniqueId);
                        int totalCount_son_succ = wxworkUserService.groupSendMsgByDeviceUniqueId(wxworkUserBatchSendMsgDto_deviceUniqueId);
                        totalCount_parent_succ = totalCount_parent_succ + totalCount_son_succ;
                    }catch (Exception e){
                        logger.error("-------sendMessageToUserSelectedSync is error; deviceUniqueId={}, error={}", deviceWxworkInfo.getId(), e.getMessage());
                    }
                }
            }
        }

        //全部执行完成之后，修改主任务状态
        if(wxworkUserBatchSendMsgDto.getGroupSendJobParentId() != null){
            GroupSendJob groupSendJob = groupSendJobMapper.selectById(wxworkUserBatchSendMsgDto.getGroupSendJobParentId(), wxworkUserBatchSendMsgDto.getMerId());
            if(groupSendJob != null){
                groupSendJob.setStatus(GroupSendStatusEnum.NOT_START.getValue()); //将状态设置为未开始状态
                groupSendJob.setTotalCount(totalCount_parent_succ);
                groupSendJobMapper.updateTotalCountById(groupSendJob);

                //批量修改子任务的状态
                groupSendJobMapper.updateStatusByParentId(GroupSendStatusEnum.NOT_START.getValue(), wxworkUserBatchSendMsgDto.getGroupSendJobParentId(), wxworkUserBatchSendMsgDto.getMerId());
            }
        }
    }

    /**
     * 多选框选择会员添加群发任务
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxworkUserSendMsgBatchDto
     * @return null
     */
    @Async("taskExecutor")
    @Override
    public void sendMessageToUserBatchSync(WxworkUserSendMsgBatchDto wxworkUserSendMsgBatchDto){
        //记录发送总数
        int totalCount_parent_succ = 0;

        //查询该运营商所有得机器人
        DeviceWxworkInfoQuery deviceWxworkInfoQuery = new DeviceWxworkInfoQuery();
        deviceWxworkInfoQuery.setMerId(wxworkUserSendMsgBatchDto.getMerId());
        List<DeviceWxworkInfo> deviceWxworkInfoList = deviceWxworkInfoMapper.findByList(deviceWxworkInfoQuery);
        if(deviceWxworkInfoList != null && deviceWxworkInfoList.size() > 0){
            for(DeviceWxworkInfo deviceWxworkInfo : deviceWxworkInfoList){
                try{
                    WxworkUserSendMsgBatchDto wxworkUserSendMsgBatchDto_deviceUniqueId = new WxworkUserSendMsgBatchDto();
                    wxworkUserSendMsgBatchDto_deviceUniqueId.setMerId(wxworkUserSendMsgBatchDto.getMerId());
                    wxworkUserSendMsgBatchDto_deviceUniqueId.setWxworkUserGroupSendMsgDto(wxworkUserSendMsgBatchDto.getWxworkUserGroupSendMsgDto());
                    wxworkUserSendMsgBatchDto_deviceUniqueId.setGroupSendJobParentId(wxworkUserSendMsgBatchDto.getGroupSendJobParentId());
                    wxworkUserSendMsgBatchDto_deviceUniqueId.setDeviceUniqueId(deviceWxworkInfo.getId());
                    wxworkUserSendMsgBatchDto_deviceUniqueId.setIdList(wxworkUserSendMsgBatchDto.getIdList());
                    int totalCount_son_succ = wxworkUserService.groupSendMsgByDeviceUniqueIdBatch(wxworkUserSendMsgBatchDto_deviceUniqueId);
                    totalCount_parent_succ = totalCount_parent_succ + totalCount_son_succ;
                }catch (Exception e){
                    logger.error("-------sendMessageToUserBatchSync is error; deviceUniqueId={}, error={}", deviceWxworkInfo.getId(), e.getMessage());
                }
            }
        }

        //全部执行完成之后，修改主任务状态
        if(wxworkUserSendMsgBatchDto.getGroupSendJobParentId() != null){
            GroupSendJob groupSendJob = groupSendJobMapper.selectById(wxworkUserSendMsgBatchDto.getGroupSendJobParentId(), wxworkUserSendMsgBatchDto.getMerId());
            if(groupSendJob != null){
                groupSendJob.setStatus(GroupSendStatusEnum.NOT_START.getValue()); //将状态设置为未开始状态
                groupSendJob.setTotalCount(totalCount_parent_succ);
                groupSendJobMapper.updateTotalCountById(groupSendJob);

                //批量修改子任务的状态
                groupSendJobMapper.updateStatusByParentId(GroupSendStatusEnum.NOT_START.getValue(), wxworkUserSendMsgBatchDto.getGroupSendJobParentId(), wxworkUserSendMsgBatchDto.getMerId());
            }
        }
    }

    /**
     * 查询结果定投筛选
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxworkUserBatchOptCpcDto
     * @return null
     */
    @Async("taskExecutor")
    @Override
    public void optCpcToUserSelected(WxworkUserBatchOptCpcDto wxworkUserBatchOptCpcDto){
        if(wxworkUserBatchOptCpcDto.getMerId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        WxworkUserOptCpcDto wxworkUserOptCpcDto =  wxworkUserBatchOptCpcDto.getWxworkUserOptCpcDto();
        if(wxworkUserOptCpcDto == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        if(wxworkUserOptCpcDto.getCpaId() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择定投项目");
        }

        Page<WxworkUser> page = new Page<>();
        page.setSize(10);
        List<WxworkUser> wxworkUserList = wxworkUserMapper.findByList(page, wxworkUserBatchOptCpcDto.getWxworkUserQuery());
//        while (wxworkUserList != null && wxworkUserList.size() > 0){
//            for (WxworkUser wxworkUser : wxworkUserList){
//                wxworkUserOptCpcDto.setId(wxworkUser.getId());
//                wxworkUserService.optCpcToOneUser(wxworkUserOptCpcDto);
//            }
//            //每次查询第一页
//            wxworkUserList = wxworkUserMapper.findByList(page, wxworkUserBatchOptCpcDto.getWxworkUserQuery());
//        }
    }

    /**
     * 查询结果批量修改
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxworkUserBatchUpdateDto
     * @return null
     */
    @Async("taskExecutor")
    @Override
    public void batchUpdateToUserSelected(WxworkUserBatchUpdateDto wxworkUserBatchUpdateDto){

        if(wxworkUserBatchUpdateDto.getMerId() == null ){
            return;
        }

        if(wxworkUserBatchUpdateDto.getWxworkUserUpdateDto() == null){
            return;
        }

        WxworkUserQuery wxworkUserQuery = wxworkUserBatchUpdateDto.getWxworkUserQuery();
        wxworkUserQuery.setMerId(wxworkUserBatchUpdateDto.getMerId());

        //查询总数
        Integer count = wxworkUserMapper.findCount(wxworkUserQuery);
        //每页个数
        int size = 10;

        if(Tools.getInteger(count) > 0 ){
            int totalPage = count / size + 1; //总页数
            for(int i = totalPage ; i>0;  i--){
                //每个时间段分页查询，每页200个
                Page<WxworkUser> page = new Page<>();
                page.setCurrent(i);
                page.setSize(size);
                List<WxworkUser> wxworkUserList = wxworkUserMapper.findByList(page, wxworkUserQuery);
                if(wxworkUserList != null && wxworkUserList.size() > 0){
                    for(WxworkUser wxworkUser : wxworkUserList) {
                        try {
                            WxworkUserUpdateDto wxworkUserUpdateDto = new WxworkUserUpdateDto();
                            //赋值
                            BeanUtils.copyProperties(wxworkUserBatchUpdateDto.getWxworkUserUpdateDto(), wxworkUserUpdateDto);
                            wxworkUserUpdateDto.setMerId(wxworkUserBatchUpdateDto.getMerId());
                            wxworkUserUpdateDto.setId(wxworkUser.getId());
                            wxworkUserUpdateDto.setLoginToken(wxworkUserBatchUpdateDto.getLoginToken());
                            wxworkUserService.updateToOneUser(wxworkUserUpdateDto);

                            //营销奖励黑名单
                            //marketingRewardsBlackListService.addOrRemoveByFlag(wxworkUser.getMerId(), wxworkUser.getBizUserId(), wxworkUserUpdateDto.getMarketingRewardsBlackListRemark(), wxworkUserUpdateDto.getMarketingRewardsBlackListFlag());

                        } catch (Exception e) {
                            logger.error("-------updateToOneUser is error userId={}, error={}", wxworkUser.getId(), e.getMessage());
                        }
                    }
                }
            }
        }

//        //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
//        WxworkMinMaxCreateTimeVo wxworkMinMaxCreateTimeVo = wxworkUserMapper.findMinAndMaxCreateTime(wxworkUserQuery);
//        //有总数，且最小创建时间有
//        if(wxworkMinMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
//            //则循环查询5天内的创建的会员
//            int duration = 5 * 24 * 3600;
//            List<TimeVO> timeVOList = DateUtil.getTimeScope(wxworkMinMaxCreateTimeVo.getMinCreateTime(), wxworkMinMaxCreateTimeVo.getMaxCreateTime(), duration);
//            if (timeVOList != null && timeVOList.size() > 0) {
//                for (TimeVO timeVO : timeVOList) {
//                    wxworkUserQuery.setCreateTimeStart(timeVO.getBeginTime());
//                    wxworkUserQuery.setCreateTimeEnd(timeVO.getEndTime());
//
//                    //每个时间段分页查询，每页200个
//                    Page<WxworkUser> page = new Page<>();
//                    int current = 1;
//                    page.setCurrent(current);
//                    page.setSize(10);//最大支持10，如果此时间段数据大于10，则分页查询
//
//                    List<WxworkUser> wxworkUserList = wxworkUserMapper.findByList(page, wxworkUserQuery);
//                    while (wxworkUserList != null && wxworkUserList.size() > 0){
//                        for(WxworkUser wxworkUser : wxworkUserList) {
//                            try {
//                                WxworkUserUpdateDto wxworkUserUpdateDto = new WxworkUserUpdateDto();
//                                //赋值
//                                BeanUtils.copyProperties(wxworkUserBatchUpdateDto.getWxworkUserUpdateDto(), wxworkUserUpdateDto);
//                                wxworkUserUpdateDto.setMerId(wxworkUserBatchUpdateDto.getMerId());
//                                wxworkUserUpdateDto.setId(wxworkUser.getId());
//                                wxworkUserService.updateToOneUser(wxworkUserUpdateDto);
//                            } catch (Exception e) {
//                                logger.error("-------updateToOneUser is error userId={}, error={}", wxworkUser.getId(), e.getMessage());
//                            }
//                            WxworkUserUpdateDto wxworkUserUpdateDto = wxworkUserBatchUpdateDto.getWxworkUserUpdateDto();
//                            marketingRewardsBlackListService.addOrRemoveByFlag(wxworkUser.getMerId(), wxworkUser.getBizUserId(), wxworkUserUpdateDto.getMarketingRewardsBlackListRemark(), wxworkUserUpdateDto.getMarketingRewardsBlackListFlag());
//                        }
//                        //再次查询下一页
//                        current ++;
//                        page.setCurrent(current);
//                        wxworkUserList = wxworkUserMapper.findByList(page, wxworkUserQuery);
//                    }
//                }
//            }
//        }
    }


    /**
     * 批量修改（多选框选择会员）
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxworkUserUpdateBatchDto
     * @return null
     */
    @Async("taskExecutor")
    @Override
    public void batchUpdateToUserBatch(WxworkUserUpdateBatchDto wxworkUserUpdateBatchDto){
        if(wxworkUserUpdateBatchDto.getMerId() == null ){
            return;
        }

        if(wxworkUserUpdateBatchDto.getWxworkUserUpdateDto() == null){
            return;
        }

        List<Long> idList = wxworkUserUpdateBatchDto.getIdList();
        if(idList == null || idList.size() == 0){
            return;
        }

        if(idList != null && idList.size() > 0){
            //查询所有机器人
            for(Long id : idList){
                try{
                    WxworkUserUpdateDto wxworkUserUpdateDto = new WxworkUserUpdateDto();
                    //赋值
                    BeanUtils.copyProperties(wxworkUserUpdateBatchDto.getWxworkUserUpdateDto(), wxworkUserUpdateDto);
                    wxworkUserUpdateDto.setMerId(wxworkUserUpdateBatchDto.getMerId());
                    wxworkUserUpdateDto.setId(id);
                    wxworkUserUpdateDto.setLoginToken(wxworkUserUpdateBatchDto.getLoginToken());
                    wxworkUserService.updateToOneUser(wxworkUserUpdateDto);
                }catch (Exception e){
                    logger.error("-------updateToOneUser is error userId={}, error={}", id, e.getMessage());
                }
            }
        }
    }

    /**
     * 删除所有查询的会员数据
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxworkUserBatchDeleteDto
     * @return null
     */
    public void deleteUserSelected(WxworkUserBatchDeleteDto wxworkUserBatchDeleteDto){

        Long merId = wxworkUserBatchDeleteDto.getMerId();
        Merchant merchant = merchantService.findByMerId(merId);
        if(merchant == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商不存在");
        }

        //查询运营商短信验证功能信息
        boolean smsCodeFlag = true;
        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(merId, MerConfigKeyEnum.SMS_CODE_CONFIG.getValue());
        if (merBaseConfig != null) {
            SmsCodeVo smsCodeVo = JSONObject.parseObject(merBaseConfig.getVal(), SmsCodeVo.class);
            if(smsCodeVo != null && smsCodeVo.getWxworkUserDelByQuery() == 0){ //不需要认证
                smsCodeFlag = false;
            }
        }

        if(smsCodeFlag){
            //如果输入的验证码不是系统通用密码，则需要验证
            if(!uzaiConsoleSysConfig.getDefaultPassword().equals(wxworkUserBatchDeleteDto.getCode())){
                //获取存在redis中的验证码
                String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.USER_DATA_DELETE.getDesc(), merchant.getMobile()));
                //判断验证码是否过期
                if (StringUtils.isBlank(codeByRedis)){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
                }
                //验证码是否正确
                if (!codeByRedis.equals(wxworkUserBatchDeleteDto.getCode()) && !uzaiConsoleSysConfig.getDefaultPassword().equals(wxworkUserBatchDeleteDto.getCode())){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
                }
                //验证成功，删除验证码
                redisTemplate.delete(String.format(SmsType.USER_DATA_DELETE.getDesc(), merchant.getMobile()));
            }
        }

        WxworkUserQuery wxworkUserQuery = wxworkUserBatchDeleteDto.getWxworkUserQuery();
        wxworkUserQuery.setMerId(wxworkUserBatchDeleteDto.getMerId());

        //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
        WxworkMinMaxCreateTimeVo wxworkMinMaxCreateTimeVo = wxworkUserMapper.findMinAndMaxCreateTime(wxworkUserQuery);
        //查询总数
        Integer count = wxworkUserMapper.findCount(wxworkUserQuery);
        //有总数，且最小创建时间有
        if(wxworkMinMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
            //则循环查询5天内的创建的会员
            int duration = 5 * 24 * 3600;
            List<TimeVO> timeVOList = DateUtil.getTimeScope(wxworkMinMaxCreateTimeVo.getMinCreateTime(), wxworkMinMaxCreateTimeVo.getMaxCreateTime(), duration);
            if (timeVOList != null && timeVOList.size() > 0) {
                for (TimeVO timeVO : timeVOList) {
                    wxworkUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                    wxworkUserQuery.setCreateTimeEnd(timeVO.getEndTime());

                    //每个时间段分页查询，每页200个
                    Page<WxworkUser> page = new Page<>();
                    int current = 1;
                    page.setCurrent(current);
                    page.setSize(10);//最大支持10，如果此时间段数据大于10，则分页查询

                    List<WxworkUser> wxworkUserList = wxworkUserMapper.findByList(page, wxworkUserQuery);
                    while (wxworkUserList != null && wxworkUserList.size() > 0){
                        for (WxworkUser wxworkUser : wxworkUserList){
                            try{
                                wxworkUserService.deleteUserById(wxworkUser.getId(), wxworkUserQuery.getMerId());
                            }catch (Exception e){
                                logger.error("-------deleteUserById is error userId={}, error={}", wxworkUser.getId(), e.getMessage());
                            }
                        }
                        wxworkUserList = wxworkUserMapper.findByList(page, wxworkUserQuery);
                    }
                }
            }
        }
    }

    /**
     * 批量删除会员数据（多选框）
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxworkUserIdListDto
     * @return null
     */
    public void deleteUserBatch(WxworkUserIdListDto wxworkUserIdListDto){
        Long merId = wxworkUserIdListDto.getMerId();
        Merchant merchant = merchantService.findByMerId(merId);
        if(merchant == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商不存在");
        }

        //查询运营商短信验证功能信息
        boolean smsCodeFlag = true;
        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(merId, MerConfigKeyEnum.SMS_CODE_CONFIG.getValue());
        if (merBaseConfig != null) {
            SmsCodeVo smsCodeVo = JSONObject.parseObject(merBaseConfig.getVal(), SmsCodeVo.class);
            if(smsCodeVo != null && smsCodeVo.getWxworkUserDelBySelected() == 0){ //不需要认证
                smsCodeFlag = false;
            }
        }

        if(smsCodeFlag){
            //如果输入的验证码不是系统通用密码，则需要验证
            if(!uzaiConsoleSysConfig.getDefaultPassword().equals(wxworkUserIdListDto.getCode())){
                //获取存在redis中的验证码
                String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.USER_DATA_DELETE.getDesc(), merchant.getMobile()));
                //判断验证码是否过期
                if (StringUtils.isBlank(codeByRedis)){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
                }
                //验证码是否正确
                if (!codeByRedis.equals(wxworkUserIdListDto.getCode()) && !uzaiConsoleSysConfig.getDefaultPassword().equals(wxworkUserIdListDto.getCode())){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
                }
                //验证成功，删除验证码
                redisTemplate.delete(String.format(SmsType.USER_DATA_DELETE.getDesc(), merchant.getMobile()));
            }
        }

        //封装批量删除的用户ID
        List<Long> idList = wxworkUserIdListDto.getIdList();
        if(wxworkUserIdListDto.getIdList() != null && wxworkUserIdListDto.getIdList().size() > 0){
            for (Long id : idList){
                try {
                    wxworkUserService.deleteUserById(id, wxworkUserIdListDto.getMerId());
                }catch (Exception e){
                    logger.error("-------deleteUserById is error userId={}, error={}", id, e.getMessage());
                }
            }
        }
    }

    /**
     * 批量删除下级会员数据（多选框）
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxworkUserDeleteSonBatchDto
     * @return null
     */
    public void deleteSonWxworkUserBatch(WxworkUserDeleteSonBatchDto wxworkUserDeleteSonBatchDto){

        Integer identity = wxworkUserDeleteSonBatchDto.getIdentity();
        if(identity == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入身份参数");
        }

        //封装批量删除的用户ID
        List<Long> idList = wxworkUserDeleteSonBatchDto.getIdList();
        if(idList == null || idList.size() == 0){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择输入的下级会员");
        }
        for (Long id : idList){
            try {
                WxworkUserDeleteSonDto wxworkUserDeleteSonDto = new WxworkUserDeleteSonDto();
                BeanUtils.copyProperties(wxworkUserDeleteSonBatchDto, wxworkUserDeleteSonDto);
                wxworkUserDeleteSonDto.setMerId(wxworkUserDeleteSonBatchDto.getMerId());
                wxworkUserDeleteSonDto.setId(id);
                wxworkUserDeleteSonDto.setIdentity(identity);
                wxworkUserService.deleteSonWxworkUser(wxworkUserDeleteSonDto);
            }catch (Exception e){
                logger.error("-------deleteSonWxworkUser is error userId={}, error={}", id, e.getMessage());
            }
        }
    }

    /**
     * 异步修改个人微信默认客户端
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxworkBatchUpdateDefaultClientDto
     * @return null
     */
    @Async("taskExecutor")
    public void updateDefaultClientSync(WxworkBatchUpdateDefaultClientDto wxworkBatchUpdateDefaultClientDto){
        Long merId = wxworkBatchUpdateDefaultClientDto.getMerId();
        if(merId == null){
            return;
        }

        Long deviceUniqueIdOld = wxworkBatchUpdateDefaultClientDto.getDeviceUniqueIdOld();
        if(deviceUniqueIdOld == null ){
            return;
        }

        Long deviceUniqueIdNew = wxworkBatchUpdateDefaultClientDto.getDeviceUniqueIdNew();
        if(deviceUniqueIdNew == null ){
            return;
        }

        List<Long> userTypeIdOldList = wxworkBatchUpdateDefaultClientDto.getUserTypeIdOldList();

        if(userTypeIdOldList == null || userTypeIdOldList.size() == 0){
            return;
        }

        List<Long> userTypeIdNewList = wxworkBatchUpdateDefaultClientDto.getUserTypeIdNewList();
        if(userTypeIdNewList == null || userTypeIdNewList.size() == 0){
            return;
        }

        //是否转移订单默认客户端
        Integer transferDataFlag =  wxworkBatchUpdateDefaultClientDto.getTransferDataFlag();
        if(Tools.getInteger(transferDataFlag).intValue() == 1){ //转移订单的默认客户端
            //转移淘宝订单
            tbOrderMapper.batchUpdateDeviceInfo(deviceUniqueIdOld, deviceUniqueIdNew, merId);
            //转移京东订单
            jdOrderMapper.batchUpdateDeviceInfo(deviceUniqueIdOld, deviceUniqueIdNew, merId);
            //转移拼多多订单
            pddOrderMapper.batchUpdateDeviceInfo(deviceUniqueIdOld, deviceUniqueIdNew, merId);
            //转移唯品会订单
            vphOrderMapper.batchUpdateDeviceInfo(deviceUniqueIdOld, deviceUniqueIdNew, merId);
            //转移美团订单
            mtOrderMapper.batchUpdateDeviceInfo(deviceUniqueIdOld, deviceUniqueIdNew, merId);
            //转移抖音订单
            dyOrderMapper.batchUpdateDeviceInfo(deviceUniqueIdOld, deviceUniqueIdNew, merId);
        }


        //新的会员类型列表长度必须大于旧的会员类型列表长度
        if(userTypeIdNewList.size() < userTypeIdOldList.size()){
            return;
        }

        for(int i=0; i<userTypeIdOldList.size(); i++){

            Long userTypeIdOld = userTypeIdOldList.get(i);
            UserType userTypeOld = userTypeMapper.selectById(userTypeIdOld, merId);
            if(userTypeOld == null){
                continue;
            }

            Long userTypeIdNew = userTypeIdNewList.get(i);
            UserType userTypeNew = userTypeMapper.selectById(userTypeIdNew, merId);
            if(userTypeNew == null){
                continue;
            }

            //身份不一样，则跳过不修改
            if(Tools.getInteger(userTypeOld.getIdentity()).intValue() != Tools.getInteger(userTypeNew.getIdentity()).intValue()){
                continue;
            }

            //修改会员默认客户端
            WxworkUpdateDefaultClient wxworkUpdateDefaultClient  = new WxworkUpdateDefaultClient();
            wxworkUpdateDefaultClient.setMerId(merId);
            wxworkUpdateDefaultClient.setDeviceUniqueIdOld(deviceUniqueIdOld);
            wxworkUpdateDefaultClient.setDeviceUniqueIdNew(deviceUniqueIdNew);
            wxworkUpdateDefaultClient.setUserTypeIdOld(userTypeIdOld);
            wxworkUpdateDefaultClient.setUserTypeIdNew(userTypeIdNew);
            wxworkUserMapper.updateDefaultClient(wxworkUpdateDefaultClient);
        }
    }

    /**
     * 查询结果批量修改营销奖励信息
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxworkUserUpdateMarketingRewardByQueryResultDto
     * @return null
     */
    @Async("taskExecutor")
    @Override
    public void updateMarketingRewardByQueryResult(WxworkUserUpdateMarketingRewardByQueryResultDto wxworkUserUpdateMarketingRewardByQueryResultDto){

        if(wxworkUserUpdateMarketingRewardByQueryResultDto.getMerId() == null ){
            return;
        }

        if(wxworkUserUpdateMarketingRewardByQueryResultDto.getMarketingReward() == null){
            return;
        }

        WxworkUserQuery wxworkUserQuery = wxworkUserUpdateMarketingRewardByQueryResultDto.getWxworkUserQuery();
        wxworkUserQuery.setMerId(wxworkUserUpdateMarketingRewardByQueryResultDto.getMerId());
        //查询总数
        Integer count = wxworkUserMapper.findCount(wxworkUserQuery);
        //每页个数
        int size = 10;

        if(Tools.getInteger(count) > 0 ){
            int totalPage = count / size + 1; //总页数
            for(int i = totalPage ; i>0;  i--){
                //每个时间段分页查询，每页200个
                Page<WxworkUser> page = new Page<>();
                page.setCurrent(i);
                page.setSize(size);
                List<WxworkUser> wxworkUserList = wxworkUserMapper.findByList(page, wxworkUserQuery);
                if(wxworkUserList != null && wxworkUserList.size() > 0){
                    for(WxworkUser wxworkUser : wxworkUserList) {
                        try {
                            UpdateMarketingRewardDto updateMarketingRewardDto = new UpdateMarketingRewardDto();
                            //赋值
                            BeanUtils.copyProperties(wxworkUserUpdateMarketingRewardByQueryResultDto.getMarketingReward(), updateMarketingRewardDto);
                            updateMarketingRewardDto.setMerId(wxworkUserUpdateMarketingRewardByQueryResultDto.getMerId());
                            updateMarketingRewardDto.setId(wxworkUser.getId());
                            updateMarketingRewardDto.setMarketingReward(wxworkUserUpdateMarketingRewardByQueryResultDto.getMarketingReward());
                            wxworkUserService.updateMarketingReward(updateMarketingRewardDto);
                        } catch (Exception e) {
                            logger.error("-------updateMarketingReward is error userId={}, error={}", wxworkUser.getId(), e.getMessage());
                        }
                    }
                }
            }
        }
    }

}
